App({

  /**
   * 全局变量
   */
  globalData: {
    appid: 'wxb02556210e4', //小程序appid
    secret: 'bb3f7ea8dd626c81168e1705302', //小程序secret
    siteBaseUrl: "https://api.niuteam.cn/", //服务器url
    wx_info: null,
    session_key: '',
    openid: '',
    token: '',
    defaultImg: {
      is_use: 0
    },
  },

  //app初始化函数
  onLaunch: function () {
    this.app_login();
    this.defaultImg();
  },
  onShow: function () {
  },
  //app登录
  app_login:function(){
    let that=this;
    wx.login({
      success: function (res) {
        if (that.globalData.session_key!=''){
          return false;
        }
        let appid = that.globalData.appid;
        let secret = that.globalData.secret;

        that.sendRequest({
          url: "api.php?s=Login/getWechatInfo",
          data: {
            appid: appid,
            secret: secret,
            code: res.code
          },
          method: "POST",
          success: function (wechat_res) {
            let code = wechat_res.code;
            if (code == 0) {
              let wx_info = JSON.parse(wechat_res.data);
              that.setSessionKey(wx_info.session_key);
              that.setOpenid(wx_info.openid);
              that.getwechatUserInfo();
            }
            // console.log(wechat_res)
          }
        });
      }
    });
  },
  getwechatUserInfo: function(){
    let that = this;
    // 获取用户信息
    wx.getSetting({
      success: (res) => {
        wx.getUserInfo({
          success: res => {
            // 可以将 res 发送给后台解码出 unionId
            that.setWxInfo(res.rawData);
            //wx.setStorageSync("userInfo", res.rawData);
            // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
            // 所以此处加入 callback 以防止这种情况
            if (this.userInfoReadyCallback) {
              this.userInfoReadyCallback(res)
            }
            that.wechatLogin(); //自动登录或注册
          }
        })
      }
    })
  },
  wechatLogin: function(){
    let that = this;
    let openid = that.globalData.openid;
    let wx_info = that.globalData.wx_info;
    //console.log(openid)
    that.sendRequest({
      url: "api.php?s=login/wechatLogin",
      data: {
        openid: openid,
        wx_info: wx_info
      },
      method: "POST",
      success: function (res) {
        let code = res.code;
        if (code == 0 || code == 10){
          that.setToken(res.data.token);
        }
        // console.log(res)
      }
    });
  },
  //封装请求函数
  sendRequest: function (param, customSiteUrl) {
    let that = this;
    let data = param.data || {};
    let header = param.header;
    let requestUrl;
    data.token = that.globalData.token;

    if (param.method == '' || param.method == undefined){
      param.method = 'POST';
    }
    if (customSiteUrl) {
      requestUrl = customSiteUrl + param.url;
    } else {
      requestUrl = this.globalData.siteBaseUrl + param.url;
    }

    if (param.method) {
      if (param.method.toLowerCase() == 'post') {
        header = header || {
          'content-type': 'application/x-www-form-urlencoded;'
        }
      }else{
        data = this._modifyPostParam(data);
      }
      param.method = param.method.toUpperCase();
    }

    if (!param.hideLoading) {
      this.showToast({
        title: '请求中...',
        icon: 'loading'
      });
    }
    
    wx.request({
      url: requestUrl,
      data: data,
      method: param.method || 'GET',
      header: header || {
        'content-type': 'application/json'
      },
      success: function (res) {
        //请求失败
        if (res.statusCode && res.statusCode != 200) {
          that.hideToast();
          /*that.showModal({
            content: '' + res.errMsg
          });*/
          typeof param.successStatusAbnormal == 'function' && param.successStatusAbnormal(res.data);
          return;
        }
        typeof param.success == 'function' && param.success(res.data);
        let code = res.data.code;
        let message = res.data.message;
        if(code == -50){
          that.showModal({
            content: message,
            url: '/pages/index/index'
          })
        }else if(code == -10){
          that.showModal({
            content: message,
            code: -10,
          })
        }
        //console.log(res);
      },
      fail: function (res) {
        that.hideToast();
        that.showModal({
          content: '请求失败 ' + res.errMsg,
        })
        typeof param.fail == 'function' && param.fail(res.data);
      },
      complete: function (res) {
        param.hideLoading || that.hideToast();
        typeof param.complete == 'function' && param.complete(res.data);
      }
    });
  },
  //微信提示 函数
  showToast: function (param) {
    wx.showToast({
      title: param.title,
      icon: param.icon,
      duration: param.duration || 1500,
      success: function (res) {
        typeof param.success == 'function' && param.success(res);
      },
      fail: function (res) {
        typeof param.fail == 'function' && param.fail(res);
      },
      complete: function (res) {
        typeof param.complete == 'function' && param.complete(res);
      }
    })
  },
  //隐藏加载提示
  hideToast: function () {
    wx.hideToast();
  },
  //模态框提示
  showModal: function (param) {
    wx.showModal({
      title: param.title || '提示',
      content: param.content,
      showCancel: param.showCancel || false,
      cancelText: param.cancelText || '取消',
      cancelColor: param.cancelColor || '#000000',
      confirmText: param.confirmText || '确定',
      confirmColor: param.confirmColor || '#3CC51F',
      success: function (res) {
        if (res.confirm) {
          typeof param.confirm == 'function' && param.confirm(res);
          if (param.url != '' && param.url != undefined){
            wx.switchTab({
              url: param.url,
            })
          }

          if (param.code != '' && param.code != undefined){
            wx.navigateBack({
              delta: 1
            })
          }

        } else {
          typeof param.cancel == 'function' && param.cancel(res);
        }
      },
      fail: function (res) {
        typeof param.fail == 'function' && param.fail(res);
      },
      complete: function (res) {
        typeof param.complete == 'function' && param.complete(res);
      }
    })
  },

  _modifyPostParam: function (obj) {
    let query = '';
    let name, value, fullSubName, subName, subValue, innerObj, i;

    for (name in obj) {
      value = obj[name];

      if (value instanceof Array) {
        for (i = 0; i < value.length; ++i) {
          subValue = value[i];
          fullSubName = name + '[' + i + ']';
          innerObj = {};
          innerObj[fullSubName] = subValue;
          query += this._modifyPostParam(innerObj) + '&';
        }
      } else if (value instanceof Object) {
        for (subName in value) {
          subValue = value[subName];
          fullSubName = name + '[' + subName + ']';
          innerObj = {};
          innerObj[fullSubName] = subValue;
          query += this._modifyPostParam(innerObj) + '&';
        }
      } else if (value !== undefined && value !== null) {
        query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
      }
    }

    return query.length ? query.substr(0, query.length - 1) : query;
  },

  getSiteBaseUrl: function () {
    return this.globalData.siteBaseUrl;
  },
  setSessionKey:function(session_key){
    this.globalData.session_key = session_key;
  },
  setOpenid: function(openid){
    this.globalData.openid=openid;
  },
  setWxInfo: function (wx_info){
    this.globalData.wx_info = wx_info;
  },
  setToken: function (token){
    this.globalData.token = token;
  },

  /**
   * 界面弹框
   */
  showBox: function(that,content,time=1500){
    setTimeout(function callBack() {
      that.setData({
        prompt: content
      });
    }, 200)
    setTimeout(function callBack() {
      that.setData({
        prompt: ''
      });
    }, time+200)
  },

  /**
   * 商品默认图
   */
  defaultImg: function(){
    let that = this;

    that.sendRequest({
      url: "api.php?s=goods/getDefaultImages",
      data: {},
      success: function (res) {
        let code = res.code;
        let data = res.data;
        if(code == 0){
          that.globalData.defaultImg = data;
        }
        console.log(res);
      }
    });
  }
})